from django.http import HttpResponse  # 修正拼写错误
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
from .models import UserInfo, LoginInfo
import uuid
from django.contrib.auth.decorators import login_required  # 导入 login_required 装饰器
from django.shortcuts import render, redirect
from django.core.exceptions import ValidationError
from django.http import JsonResponse
# Create your views here.

def index(request):
    return HttpResponse("Hello, world. You're at the user index.")


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        nickname = request.POST.get('nickname', '')
        register_ip = request.META.get('REMOTE_ADDR')

        if not username or not password:
            return JsonResponse({'error': '用户名和密码不能为空'}, status=400)

        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                nickname=nickname,
                register_ip=register_ip
            )
            return JsonResponse({'message': '注册成功'}, status=201)
        except ValidationError as e:
            return JsonResponse({'error': str(e)}, status=400)
        except Exception as e:
            return JsonResponse({'error': f'注册失败: {str(e)}'}, status=400)

    return render(request, 'register.html')


def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            auth_login(request, user)
            session_sid = str(uuid.uuid4())
            LoginInfo.objects.create(
                user_info=UserInfo.objects.get(username=username),
                session_sid=session_sid
            )
            return redirect('home')  # 替换为你的主页 URL 名称
        else:
            error_message = '用户名或密码错误'
            return render(request, 'login.html', {'error_message': error_message})
    return render(request, 'login.html')


def logout(request):
    auth_logout(request)
    return redirect('login')


@login_required
def profile(request):
    return render(request, 'profile.html')


def index(request):
    return render(request, 'index.html')